package com.woniuxy.run.user.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.ResponseResult;
import com.woniuxy.run.user.entity.ConstantProperties;
import com.woniuxy.run.user.entity.Users;
import com.woniuxy.run.user.exception.AccountExsitException;
import com.woniuxy.run.user.mapper.UsersMapper;
import com.woniuxy.run.user.service.MailService;
import com.woniuxy.run.user.service.UsersService;
import com.woniuxy.run.user.utils.AliyunOSSUtil;
import com.woniuxy.run.user.utils.EmailUtil;
import com.woniuxy.run.user.utils.RedisUtil;
import com.woniuxy.run.user.utils.Request;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 
 * @since 2021-03-23
 */
@RestController
@RequestMapping("/user")
public class UsersController {

    //验证码
    private String code = "";

    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private UsersService usersService;
    @Autowired
    private MailService mailService;
    @Autowired
    private AliyunOSSUtil util;
    @Autowired
    private RedisUtil redis;

    //用户点击获取验证码按钮
    @GetMapping("/getcode")
    public ResponseResult<String> getCode(String email){
        ResponseResult<String> result = new ResponseResult<>();
        code = EmailUtil.code();
        mailService.sendMail("2350134110@qq.com",email,"注册验证码",code);
        result.setData(code);
        return result;
    }

    //注册
    @RequestMapping("/regist")
    public ResponseResult regist(@Valid Users user, String code1){
        ResponseResult result = new ResponseResult();
        //判断是否有这个用户名
        if(usersMapper.selectByAcc(user.getAccount())!=null){
           throw new AccountExsitException();
        }
        //先判断数据库是否存在该手机号，一个手机号只能注册一次
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("telphone",user.getTelphone());
        if(usersMapper.selectCount(wrapper)>0){
            result.setMsg("该手机号已经注册过了");
            result.setCode(250);
            return result;
        }
        //邮箱正则表达式
        String regex = "[\\w!#$%&'*+/=?^_`{|}~-]+(?:\\.[\\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\\w](?:[\\w-]*[\\w])?\\.)+[\\w](?:[\\w-]*[\\w])?";
        //如果邮箱格式不正确
        if(!user.getEmail().matches(regex)){
            result.setMsg("邮箱格式不正确");
            result.setCode(250);
            return result;
        }
        //判断用户输入的验证码是否正确
        if(code.equalsIgnoreCase(code1)){
            //对密码进行加密
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            user.setPwd(encoder.encode(user.getPwd()));
            usersMapper.insert(user);
            result.setCode(200);
            result.setMsg("注册成功");
        }
        //不相等
       result.setMsg("验证码输入不正确");
        result.setCode(500);
        return result;
    }

    //登录
    @PostMapping("/login")
    public ResponseResult login(String account,String pwd){
        ResponseResult result = new ResponseResult();
        //先查询出是否存在该用户
        if(usersMapper.selectByAcc(account)==null)   {
            //不存在该账户
            result.setMsg("该账户不存在");
            result.setCode(101);
            return result;
        }
        //存在该用户，查询出密码
        Users user = usersMapper.selectByAcc(account);
        //匹配秘钥
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        boolean isMatch = encoder.matches(pwd,user.getPwd());
        if(!isMatch){
            result.setMsg("密码和用户名不匹配");
            result.setCode(102);
            return result;
        }
        //生成秘钥
//        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        String datestr = df.format(new Date());

        String tokenStr = String.format("%s_%s", account, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        System.out.println("111111111111111----"+tokenStr+"");

        BCryptPasswordEncoder encoder2 = new BCryptPasswordEncoder();
        String token = encoder2.encode(tokenStr);

        System.out.println("22222222222222222----"+token+"");

        //登录成功后，存入redis缓存,加上token与其他用户的登录信息分开
        redis.set(token+"account",account,24*3600L);
        redis.set(token+"password",pwd,24*3600L);
        return ResponseResult.SUCCESS;
    }

    //修改头像
    @PostMapping("/avatar")
    public ResponseResult<String> avatar(@RequestParam MultipartFile file,String account){

       //上传头像
      String url = util.uploadFile(file);

        ResponseResult result = new ResponseResult();
        if(usersService.updateAvatar(account,url)){
            result.setMsg("修改失败");
            result.setCode(240);
            return result;
        }
        result.setMsg("修改成功");
        result.setData(url);
        result.setCode(200);
        return result;
    }


    //退出登录
    @GetMapping("/logout")
    public ResponseResult logout(){
        String token = Request.getToken();

        System.out.println(token);

        //删除redis中的用户数据
        redis.remove(token+"account");
        redis.remove(token+"password");
        return ResponseResult.SUCCESS;
    }





    //
    @GetMapping("/all")
    public ResponseResult<List<Users>> all(){
        ResponseResult result = new ResponseResult();
        result.setData(usersService.all());
        return result;
    }
}

